package data;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import viajaGratis.Solicitud;

public class SolicitudDAO {

	private Solicitud checkSolicitud(Integer id){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Solicitud peticion=(Solicitud)session.createQuery("from Solicitud as m where m.idSolicitud=?").setInteger(0,id).uniqueResult();
		return peticion;
	}
	
	public Solicitud selectById(Integer id){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Solicitud peticion=(Solicitud)session.createQuery("from Solicitud as m where m.idSolicitud=?").setInteger(0,id).uniqueResult();
		if(peticion!=null){
			Hibernate.initialize(peticion);
			Hibernate.initialize(peticion.getOferta());
			Hibernate.initialize(peticion.getSolicitante());
		}
		return peticion;
	}
	
	public void insert(Solicitud u){
		if(checkSolicitud(u.getIdSolicitud())==null){
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(u);
			session.flush();
			session.getTransaction().commit();
		}
	}
	
	public void delete(Solicitud u){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Object solicitud=session.load(Solicitud.class,u.getIdSolicitud());
		session.delete(solicitud);
		session.getTransaction().commit();
	}
	
	public void update(Solicitud u){
		if(checkSolicitud(u.getIdSolicitud())!=null){
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(u);
			session.flush();
			session.getTransaction().commit();
		}
	}
}
